package com.xuecheng.learning.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.commons.constants.CourseConstants;
import com.xuecheng.commons.constants.OrdersConstants;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.dto.LearningProgressDto;
import com.xuecheng.commons.model.dto.RecordDto;
import com.xuecheng.commons.model.vo.*;
import com.xuecheng.commons.utils.AuthInfoHolder;
import com.xuecheng.commons.utils.BeanHelper;
import com.xuecheng.content.api.ContentClient;
import com.xuecheng.learning.domain.CourseRecord;
import com.xuecheng.learning.mappers.CourseRecordMapper;
import com.xuecheng.learning.service.CourseRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.media.api.MediaClient;
import com.xuecheng.web.exceptions.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 选课记录 服务实现类
 */
@Service
public class CourseRecordServiceImpl extends ServiceImpl<CourseRecordMapper, CourseRecord> implements CourseRecordService {

    @Autowired
    private ContentClient contentClient;

    @Autowired
    private MediaClient mediaClient;

    //根据课程的发布id，查询用户对此课程的选课数据
    public ResponseResult<CourseRecordVo> findRecordByPubId(Long coursePubId) {
        LambdaQueryWrapper<CourseRecord> qw = new LambdaQueryWrapper<>();
        qw.eq(CourseRecord::getUserId, AuthInfoHolder.getUserId());
        qw.eq(CourseRecord::getCoursePubId,coursePubId);
        //查询
        CourseRecord courseRecord = this.getOne(qw);
        if(courseRecord == null) {
            return ResponseResult.okResult();
        }
        //转化
        CourseRecordVo vo = BeanHelper.copyProperties(courseRecord, CourseRecordVo.class);
        return ResponseResult.okResult(vo);
    }

    //保存或者更新选课记录(支付确认之后，调用)
    public ResponseResult saveRecord(RecordDto dto) { ;
        //1、根据用户id和课程Id查询
        LambdaQueryWrapper<CourseRecord> qw = new LambdaQueryWrapper<>();
        qw.eq(CourseRecord::getUserId,dto.getUserId());
        qw.eq(CourseRecord::getCoursePubId,dto.getCoursePubId());
        CourseRecord record = this.getOne(qw);
        //2、如果数据存在，说明之前有试听的信息
        if(record != null) {
            //2.1 修改状态
            record.setPaid(OrdersConstants.PAID);
            //2.2 更新数据库表
            this.updateById(record);
        }else{
            //3、如果数据不存在，存入数据库
            //调用contentClient查询课程发布信息
            ResponseResult<CoursePubVo> result = contentClient.findById(dto.getCoursePubId());
            CoursePubVo data = result.getData();
            record = new CourseRecord();
            record.setUserId(dto.getUserId());
            record.setCoursePubId(dto.getCoursePubId());
            record.setCompanyId(data.getCompanyId());
            record.setCourseId(data.getCourseId());
            record.setCoursePubName(data.getName());
            record.setTeachmode(data.getTeachmode());
            record.setStartTime(data.getStartTime());
            record.setEndTime(data.getEndTime());
            record.setCreateDate(new Date());
            record.setPaid(OrdersConstants.PAID);
            this.save(record);
        }

        return ResponseResult.okResult();
    }

    //查询课程的媒资信息
    public ResponseResult<ResourceVo> findPlayUrl(Long coursePubId, Long mediaId, Long teachplanId) {
        //1、查询课程，查看课程的收费状态
        ResponseResult<CoursePubVo> pubResult = contentClient.findById(coursePubId);
        CoursePubVo pubVo = pubResult.getData();
        String charge = pubVo.getCharge(); //收费状态
        if(charge.equals(CourseConstants.CHARGE_YES)) {
            //2、收费课程，判断课程的章节是否免费
            ResponseResult<TeachplanVo> planResult = contentClient.findPlanById(teachplanId);
            TeachplanVo vo = planResult.getData();
            String preview = vo.getIsPreview(); //0-收费，1-试看
            if(preview.equals("0")) {
                //3、课程章节收费，未购买
                LambdaQueryWrapper<CourseRecord> qw = new LambdaQueryWrapper<>();
                qw.eq(CourseRecord::getCoursePubId,coursePubId);
                qw.eq(CourseRecord::getUserId,AuthInfoHolder.getUserId());
                CourseRecord record = this.getOne(qw);
                //未查询到数据，或者未支付
                if(record == null || record.getPaid().equals(OrdersConstants.NOT_PAID)) {
                    throw new BusinessException(ErrorCode.ERROR);
                }
            }
        }
        return mediaClient.findMediaUrl(mediaId);
    }

    //保存或者更新学习进度
    public ResponseResult progress(LearningProgressDto dto) {
        //1、根据用户id和课程发布id查询选课记录
        LambdaQueryWrapper<CourseRecord> qw = new LambdaQueryWrapper<>();
        qw.eq(CourseRecord::getUserId,AuthInfoHolder.getUserId());
        qw.eq(CourseRecord::getCoursePubId,dto.getCoursePubId());
        CourseRecord record = this.getOne(qw);
        //2、数据存在，更新
        if(record != null) {
            record.setTeachplanId(dto.getTeachPlanId());
            record.setTeachplanName(dto.getTeachPlanName());
            this.updateById(record);
        }else {
            //3、数据不存在，保存（设置paid为0）
            record = new CourseRecord();
            record.setTeachplanId(dto.getTeachPlanId());
            record.setTeachplanName(dto.getTeachPlanName());
            record.setUserId(AuthInfoHolder.getUserId());
            //查询课程发布信息
            ResponseResult<CoursePubVo> result = contentClient.findById(dto.getCoursePubId());
            CoursePubVo data = result.getData();
            record.setCompanyId(data.getCompanyId());
            record.setCourseId(data.getCourseId());
            record.setCoursePubName(data.getName());
            record.setTeachmode(data.getTeachmode());
            record.setStartTime(data.getStartTime());
            record.setEndTime(data.getEndTime());
            record.setCreateDate(new Date());
            record.setPaid(OrdersConstants.NOT_PAID);
            this.save(record);
        }

        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult<List<CourseRecordVo>> findSelectCourse(String id) {
        LambdaQueryWrapper<CourseRecord> qw = new LambdaQueryWrapper<>();
        qw.eq(CourseRecord::getUserId,id);
        List<CourseRecord> list = this.list(qw);
        List<CourseRecordVo> courseRecordVos = BeanHelper.copyWithCollection(list, CourseRecordVo.class);
        return ResponseResult.okResult(courseRecordVos);
    }
}
